define(function(require, exports) {
	var util = require('util');
	var pubjs = require('pubjs');
	var $ = require('jquery');
	var view  = require('@base/view');
	var input = require('@base/common/input');
	var drop = require('@base/common/drop');

	// 关键词输入框
	var FlexibleHotWord = input.flexibleInput.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'intervalText': LANG('或'),
				'class': 'M-PageFlexibleHotWord'
			});

			this.Super('init', arguments);
		},
		/**
		 * 新增输入框 -按钮的回调事件
		 * @param  {object} ev 事件对象
		 */
		eventAddItem: function(ev, elm){
			var self = this;
			// 获取有多少个关键词输入框
			self.fire('getWordsAmount', function(ev) {
				if (ev.returnValue >= 5) {
					pubjs.alert(LANG('最多监控5个关键词'));
					return false;
				}
				self.buildItem();

			});
		}
	});

	/**
	 * 百度指数（关键词）模块
	 */
	var Base = view.container.extend({
		init: function(config){
			config = pubjs.conf(config, {
				'class': 'M-PageHotWord'
			});

			// 存储被删除关键模块的index；
			this.$destroyIndexList = [];
			this.Super('init', arguments);
		},
		afterBuild: function(){
			var self = this;
			var el = self.getDOM();
			var doms = self.$doms = {};

			$('<p>').text(LANG('最多监控5个关键词')).appendTo(el);
			doms.itemCon = $('<div class="M-PageHotWordCon">').appendTo(el);

			// 增加按钮
			self.createAsync('add', '@base/common/input.button',{
				'target': el,
				'value': LANG('添加“或”条件'),
				'data': 'add',
				'width': 0,
				'class': 'btn btn-default mt10'
			});

			self.uiProxy(el, '.M-PageHotWordConItemBtnDel', 'click', 'eventDelItem');

			self.reset();
		},
		reset: function(nobuild){
			var self = this;
			var cs = self.$;
			// 销毁所有模块
			for(var i = 0; i < self.$count; i++){
				// 没有被删除的关键词模块reset
				if(self.$destroyIndexList.indexOf(i) > -1){
					continue;
				}
				cs['words'+i].destroy();
				cs['target'+i].destroy();
				cs['recentCount'+i].destroy();
				cs['recentCountType'+i].destroy();
				cs['changeType'+i].destroy();
				cs['changeCount'+i].destroy();
				cs['changeCountType'+i].destroy();
				cs['changeLimit'+i].destroy();
				cs['openDays'+i].destroy();
			}
			// 清空元素，再构建
			self.$doms.itemCon.empty();
			self.$count = 0;
			if (!nobuild) {
				self.buildItem();
			}
			self.$destroyIndexList = [];
			return self;
		},
		setData: function(data){
			var self = this;
			self.$data = data;
			if (data && data.length) {
				this.reset(true);
				util.each(data, function(item){
					self.buildItem(item);
				});
			}
		},
		getData: function(){
			var data = [];
			var cs = this.$;
			for(var i = 0; i < this.$count; i++){
				// 已删除的模块continue
				if (this.$destroyIndexList.indexOf(i) > -1) {
					continue;
				}
				// 去掉判断可见
				// if(this.$doms.itemCon.find('.M-PageHotWordConItem').filter('[data-id='+i+']').is(':visible')){}
				data.push({
					Words: cs['words'+i] ? cs['words'+i].getData() : [],
					Target: cs['target'+i] ? +cs['target'+i].getValue('id') : 3,
					Change: {
						RecentCount: cs['recentCount'+i] ? +cs['recentCount'+i].getValue() : 7,
						RecentCountType: cs['recentCountType'+i] ? +cs['recentCountType'+i].getValue('id') : 1,
						ChangeType: cs['changeType'+i] ? +cs['changeType'+i].getValue('id') : 1,
						ChangeCount: cs['changeCount'+i] ? +cs['changeCount'+i].getValue() : '',
						ChangeLimit: cs['changeLimit'+i] ? +cs['changeLimit'+i].getValue() : '',
						ChangeCountType: cs['changeCountType'+i] ? +cs['changeCountType'+i].getValue('id') : 1
					},
					OpenDays: cs['openDays'+i] ? +cs['openDays'+i].getValue() : 0
				});
			}
			return data;
		},
		buildItem: function(data){
			var self = this;
			var con = self.$doms.itemCon;
			var cs = {};
			var id = self.$count || 0;

			self.$count++;

			// 文字或
			$('<p class="M-PageHotWordConOr">').html(LANG('或')).appendTo(con)[!id?'hide':'show']();
			// item容器
			var wrap = $('<div class="M-PageHotWordConItem P-campaignEditBox" data-id="'+id+'"/>').appendTo(con);
			var wordsWrap = $('<div class="mb10"/>').appendTo(wrap);

			// 关键词
			wordsWrap.append($('<span class="mr10"/>').html(LANG('关注的关键词')));
			// 关键词输入框
			cs.words = self.create('words'+id, FlexibleHotWord,{
				'label': '',
				'target': wordsWrap,
				'width': 90,
				'height': 20
			});

			// 其他内容区
			wrap.append($('<span class="mr10"/>').html(LANG('当所投')));

			cs.target = self.create('target'+id, drop.drop,{
				'target': wrap,
				'width': 100,
				'hasSearch': false,
				'value': 3,
				'options': [
					{name: LANG('国家'), id: 1},
					{name: LANG('省份'), id: 2},
					{name: LANG('城市'), id: 3}
				]
			});

			wrap.append($('<span class="mg10"/>').html(LANG('最近')));

			cs.recentCount = self.create('recentCount'+id, input.text,{
				'label': '',
				'target': wrap,
				'width': 40,
				'value': 7,
				'disabled': false
			});

			cs.recentCountType = self.create('recentCountType'+id, drop.drop,{
				'target': wrap,
				'width': 60,
				'hasSearch': false,
				'value': 1,
				'options': [
					{name: LANG('天'), id: 1}
					//,{Name: LANG('小时'), _id: 2}
				]
			}).hide();

			wrap.append($('<span class="mg10"/>').html(LANG('天，百度搜索指数上升≥')));

			cs.changeType = self.create('changeType'+id, drop.drop,{
				'target': wrap,
				'width': 100,
				'hasSearch': false,
				'value': 1,
				'options': [
					{name: LANG('上升'), id: 1},
					{name: LANG('下降'), id: 2},
					{name: LANG('上升或下降'), id: 3}
				]
			}).hide();

			cs.changeCount = self.create('changeCount'+id, input.text,{
				'label': '',
				'target': wrap,
				'width': 40,
				'value': '',
				'placeholder': '0'
			});

			cs.changeCountType = self.create('changeCountType'+id, drop.drop,{
				'target': wrap,
				'width': 50,
				'hasSearch': false,
				'value': 1,
				'options': [
					{name: LANG('%'), id: 1}
				]
			}).hide();

			wrap.append($('<span class="mg10"/>').html(LANG('% ，且搜索指数≥')));

			cs.changeLimit = self.create('changeLimit'+id, input.text,{
				'label': '',
				'target': wrap,
				'width': 40,
				'value': '',
				'placeholder': '0'
			});

			wrap.append($('<span class="mg10"/>').html(LANG('时，之后')));

			cs.openDays = self.create('openDays'+id, input.text,{
				'label': '',
				'target': wrap,
				'width': 40,
				'value': "3",
				'tips': LANG('持续投放天数填“0”天表示当天投放。')
			});

			$('<span class="mg10"/>').html(LANG('天持续投放广告')).appendTo(wrap);

			//按钮-删除item
			$('<span class="M-PageHotWordConItemBtnDel" data-id="'+id+'"></span>').appendTo(wrap)[!id?'hide':'show']();

			if(data) {
				cs.words.setData(data.Words);
				cs.target.setValue(data.Target);
				cs.recentCount.setValue(data.Change.RecentCount);
				cs.recentCountType.setValue(data.Change.RecentCountType);
				cs.changeType.setValue(data.Change.ChangeType);
				cs.changeCount.setValue(data.Change.ChangeCount);
				cs.changeCountType.setValue(data.Change.ChangeCountType);
				cs.changeLimit.setValue(data.Change.ChangeLimit);
				cs.openDays.setValue(data.OpenDays);
			}
		},
		eventDelItem: function(evt, elm){
			var cs = this.$;
			var id = $(elm).attr('data-id');

			// 销毁模块
			cs['words'+id].destroy();
			cs['target'+id].destroy();
			cs['recentCount'+id].destroy();
			cs['recentCountType'+id].destroy();
			cs['changeType'+id].destroy();
			cs['changeCount'+id].destroy();
			cs['changeCountType'+id].destroy();
			cs['changeLimit'+id].destroy();
			cs['openDays'+id].destroy();
			// 移除元素
			$(elm).parent().prev('p').remove();
			$(elm).parent().remove();

			//缓存已删除模块的index
			this.$destroyIndexList.push(+id);
			return false;
		},
		// 获取关键词的个数
		getWordsAmount: function() {
			var amount = 0;
			for(var i = 0; i < this.$count; i++) {
				// 已删除的模块continue
				if (this.$destroyIndexList.indexOf(i) > -1) {
					continue;
				}
				amount += this.$['words'+i].$amount;
			}
			return amount;
		},
		// flexibleInput获取关键词的个数
		onGetWordsAmount: function(ev) {
			ev.returnValue = this.getWordsAmount();
			return false;
		},
		onInputClick: function(ev){
			if (ev.name === 'add'){
				if(this.getWordsAmount() >= 5){
					pubjs.alert(LANG('最多监控5个关键词'));
					return false;
				}
				this.buildItem();
			}
		}
	})
	exports.base = Base;
});
